#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/COOPIP/djangoproject/include', '/opt/COOPIP/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/COOPIP/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from djangoproject.models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Ajax
import GIS


def UpdateMeterPingTemplate(FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters, UserName=''):
    FileName='/opt/coopip/djangoproject/templates/dynamic_meterping' + UserName + '.html'

    Total = 0
    ReplacementBlockList=[]  
    ReplacementBlockList.append('Meters that Failed to Respond')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td> <td>Tag</td><td>Cir</td> <td>Last Success</td><td>Last Attempt</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(FailedMeters)):
        ReplacementBlockList.append(MeterFormFailedTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')
 
    ReplacementBlockList.append('Meters that Could not be Verified in CIS')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(ActiveButNotAuthorizedMeters)):
        ReplacementBlockList.append(MeterFormActiveButNotAuthorizedTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters That Could Not be Found in the CIS')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(NotFoundMeters)):
        ReplacementBlockList.append(MeterFormNotFoundTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters With Open Service Orders')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Last Attempt</td><td>Not Verified</td><td>Inv</td><td>ServiceOrderDescription</td><td>Description</td></tr>')
    for i in range(0, len(ServiceOrderMeters)):
        ReplacementBlockList.append(MeterFormServiceOrderTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters Being Investigated')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Last Attempt</td><td>Not Verified</td><td>Inv</td><td>Description</td><td>Investigate DateTime</td></tr>')
    for i in range(0, len(InvestigationMeters)):
        ReplacementBlockList.append(MeterFormInvestigationTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=MeterFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()



MeterFormTemplate="""
<!--
#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
        #map {
            width: 800px;
            height: 600px;
            border: 1px solid black;
        }
    </style>
    {{ OpenLayersJavaScriptHeading|safe }}
    <title>COOPIP Map Viewer</title>
  </head>
  <body>
	<b>COOPIP Map Viewer </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
 <table>
<tr><td VALIGN="top"><div id="map">
 {{ OpenLayersJavaScript|safe }}
</td><td><pre>{{ManualPingMeterReport}}</pre></td></tr>
<tr><td><a href="/coopip/meterping/report/">Meter Ping Report</a><br>
Ping Meters/Substation/Circuit {{form.PingMeterCommand}}  &nbsp&nbsp&nbsp&nbsp&nbsp  <input type="submit" /> <br><table>{{Repeating Block}}</table></td></tr>


</table>
</form>

  </body>
</html>
"""



MeterFormFailedTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.GISCircuitNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.LastPingResponseDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
</tr>
 """


MeterFormActiveButNotAuthorizedTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
</tr>
 """


MeterFormNotFoundTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
</tr>
 """


MeterFormServiceOrderTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.LastPingResponseDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.ServiceOrderDescription{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
<td>{{form.InvestigationStartDateTime{{repeatnumber}}}}</td>
</tr>
 """


MeterFormInvestigationTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.LastPingResponseDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
<td>{{form.InvestigationStartDateTime{{repeatnumber}}}}</td>
</tr>
 """


def UpdateDispatchMeterPingTemplate(FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters, UserName=''):
    FileName='/opt/coopip/djangoproject/templates/dynamic_dispatchmeterping' + UserName + '.html'

    Total = 0
    ReplacementBlockList=[]  
    ReplacementBlockList.append('Meters that Failed to Respond')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td> <td>Tag</td><td>Cir</td> <td>Last Success</td><td>Last Attempt</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(FailedMeters)):
        ReplacementBlockList.append(MeterFormFailedTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')
 
    ReplacementBlockList.append('Meters that Could not be Verified in CIS')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(ActiveButNotAuthorizedMeters)):
        ReplacementBlockList.append(MeterFormActiveButNotAuthorizedTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters That Could Not be Found in the CIS')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(NotFoundMeters)):
        ReplacementBlockList.append(MeterFormNotFoundTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters With Open Service Orders')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Last Attempt</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(ServiceOrderMeters)):
        ReplacementBlockList.append(MeterFormServiceOrderTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters Being Investigated')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Last Attempt</td><td>Not Verified</td><td>Inv</td><td>Description</td><td>Investigate DateTime</td></tr>')
    for i in range(0, len(InvestigationMeters)):
        ReplacementBlockList.append(MeterFormInvestigationTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=MeterFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()









def UpdateCrewLogTemplate(Username, RepeatingBlockCount):
    FileName='/opt/coopip/djangoproject/templates/dynamic_dispatchcrewlog_' + Username + '.html'

    Total = 0
    ReplacementBlockList=[]
    #ReplacementBlockList.append('<table>')  
    ReplacementBlockList.append('<tr><td>Update</td><td>Log</td><td>Crew #</td><td>Truck</td><td>Employees</td><td>EnRoute</td><td>Arrival</td><td>Departure</td><td>Location</td><td>Pole #</td><td>Comments</td><td>Back At Office</td><td>Address</td><td>Delete</td></tr>')
    for i in range(0, RepeatingBlockCount):
        ReplacementBlockList.append('<tr><td>{{form.UpdateIndicator' + str(i) + '}}</td>' \
                                    '<td>{{form.DispatchCrewLogid' + str(i) + '}}</td>' \
                                    '<td>{{form.CrewNumber' + str(i) + '}}</td>' \
                                    '<td>{{form.TruckNumber' + str(i) + '}}</td>' \
                                    '<td>{{form.Employees' + str(i) + '}}</td>' \
                                    '<td>{{form.EnRouteDateTime' + str(i) + '}}</td>'\
                                    '<td>{{form.ArriveAtLocationDateTime' + str(i) + '}}</td>'\
                                    '<td>{{form.DepartLocationDateTime' + str(i) + '}}</td>' \
                                    '<td>{{form.LocationDescription' + str(i) + '}}</td>' \
                                    '<td>{{form.PoleNumber' + str(i) + '}}</td>' \
                                    '<td>{{form.Comments' + str(i) + '}}</td>' \
                                    '<td>{{form.BackAtOfficeDateTime' + str(i) + '}}</td>' \
                                    '<td>{{form.Address'+str(i) + '}}</td>' \
                                    '<td>{{form.DeleteIndicator'+str(i) + '}}</td></tr>')
    Total = Total + 1
    #ReplacementBlockList.append('</table>')
 
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=CrewLogTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()







CrewLogTemplate = """
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<!--#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.-->

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>dispatchcrewlog.html</title>
  <link rel="stylesheet" type="text/css" href="/style.css" />
</head>

<body style="background-image:url('/intranetbackgroundimages/{{DepartmentBackgroundImage}}');background-size: 100%;background-color:rgb(210,210,250);background-repeat: no-repeat;">


<div id="logo">
    <img src="/media/TCECLogo.png" name="graphics1" align="left" border="0" height="84" width="198">
</div>

<div id="login">
    <table>
    <tr><td>{{LoginStatus}}</td><td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<small><a href="/coopip/">Main Menu</a></small></td></tr>
    </table>
    <br><br>
</div>



{% if Permission %}
<div id="dispatchcrewlogform">
    <h1>Dispatch Crew Log</h1>
    <form method="post" action="">
    <table>
    <tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td><input type="submit" /></td><td><a href="/coopip/dispatch/view/crewloghistory/">Log History</a></td></tr>
    <tr><td>New</td><td>id</td><td>Crew #</td><td>Truck</td><td>Employees</td><td>EnRoute</td><td>Arrival</td><td>Departure</td><td>Location</td><td>Pole #</td><td>Comments</td><td>Back At Office</td><td>Address</td></tr>
    <tr><td>{{form.NewIndicator}}</td><td>&nbsp</td><td>{{form.CrewNumberNew}}</td><td>{{form.TruckNumberNew}}</td><td>{{form.EmployeesNew}}</td><td>{{form.EnRouteDateTimeNew}}</td><td>{{form.ArriveAtLocationDateTimeNew}}</td>
        <td>{{form.DepartLocationDateTimeNew}}</td><td>{{form.LocationDescriptionNew}}</td><td>{{form.PoleNumberNew}}</td><td>{{form.CommentsNew}}</td><td>{{form.BackAtOfficeDateTimeNew}}</td>
        <td>{{form.AddressNew}}</td></tr>
    <tr><td>&nbsp</td></tr>
   
    {{Repeating Block}}
    </table>
    </form>
</div>

{% endif %}

</body></html>
"""








MeterInvestigationFormTemplate="""
<!--
#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
        #map {
            width: 800px;
            height: 600px;
            border: 1px solid black;
        }
    </style>
    {{ OpenLayersJavaScriptHeading|safe }}
    <title>COOPIP Meter Investigation</title>
    <link rel="stylesheet" type="text/css" href="/style.css" />
  </head>
  <body style="background-image:url('/intranetbackgroundimages/{{DepartmentBackgroundImage}}');background-size: 100%;background-color:rgb(210,210,250);background-repeat: no-repeat;">
<div id="meterinvestigation_wrap">
<div id="meterinvestigation_left">
<b>COOPIP Map Viewer </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">

<table>
<tr><th>Meter#</th><th>Disconnected</th><th>Previous Read Date</th><th>KWH</th><th>LatestReadDate</th><th>KWH</th></tr>
{%for row in NotAuthorizedReport%}
    <tr>
    {%for entry in row%}
        {%if forloop.first%}
            <td>{{entry}}</td>
        {%else%}
            <td style="text-align:right;">{{entry}}</td>
        {%endif%}
    {%endfor%}
    </tr>
{%endfor%}
</table>
<table>
<tr><td><input type="submit" /> </td></tr>
    {{Repeating Block}}
</table>
</div>
<div id="meterinvestigation_right">
<table>
<tr>
    <td VALIGN="top"><div id="map"> {{ OpenLayersJavaScript|safe }}</td>
    <td><pre>{{ManualPingMeterReport}}</pre></td>
</tr>

</table>
</div>
</div>
</form>
</body>
</html>"""


MeterInvestigationFormActiveButNotAuthorizedTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
</tr>
"""

MeterInvestigationFormInvestigationTemplateRepeatingBlock="""
<tr>
<td>{{form.UpdateIndicator{{repeatnumber}}}}</td>
<td>{{form.MeterNumber{{repeatnumber}}}}</td> 
<td>{{form.TagNumber{{repeatnumber}}}}</td>
<td>{{form.LastSuccessfulPingDateTime{{repeatnumber}}}}</td>
<td>{{form.LastPingResponseDateTime{{repeatnumber}}}}</td>
<td>{{form.AppearedOnNotVerifiedListDateTime{{repeatnumber}}}}</td>
<td>{{form.InvestigationIndicator{{repeatnumber}}}}</td>
<td>{{form.Description{{repeatnumber}}}}</td>
<td>{{form.InvestigationStartDateTime{{repeatnumber}}}}</td>
</tr>
 """



def UpdateMeterInvestigationTemplate(ActiveButNotAuthorizedMeters, InvestigationMeters, UserName=''):
    FileName='/opt/coopip/djangoproject/templates/dynamic_meterinvestigation' + UserName + '.html'
    Total = 0
    ReplacementBlockList=[]  
    ReplacementBlockList.append('Meters that are Active But Not Authorized (Not Verified in CIS)')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Not Verified</td><td>Inv</td><td>Description</td></tr>')
    for i in range(0, len(ActiveButNotAuthorizedMeters)):
        ReplacementBlockList.append(MeterInvestigationFormActiveButNotAuthorizedTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')

    ReplacementBlockList.append('Meters Being Investigated')
    ReplacementBlockList.append('<table><tr><td>Upd</td><td>Meter</td><td>Tag</td><td>Last Success</td><td>Last Attempt</td><td>Not Verified</td><td>Inv</td><td>Description</td><td>Investigate DateTime</td></tr>')
    for i in range(0, len(InvestigationMeters)):
        ReplacementBlockList.append(MeterInvestigationFormInvestigationTemplateRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total = Total + 1
    ReplacementBlockList.append('</table>')
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=MeterInvestigationFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()

NetworkDeviceAddEditFormTemplate="""
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<!--#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.-->

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>networkdeviceaddedit.html</title>
  <link rel="stylesheet" type="text/css" href="http://192.168.100.54/style.css" />
</head>

<body>

<div id="logo">
    <img src="/media/TCECLogo.png" name="graphics1" align="left" border="0" height="84" width="198">
</div>

<div id="login">
    {% if not Permission %}
    <form method="post" action="">
    Login:  {{form.Username}} Password:  {{form.Password}} <input value="Login" type="submit">
    {% else %}  <!---# else...  display the rest of the page -->
    {{LoginStatus}} &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<a href="/coopip/revenueprotection/logout/">Logout</a> 
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<a href="http://192.168.100.54/coopip/revenueprotection/">Revenue Protection Main Menu</a>
</div>



<h1>Network Device Add/Edit</h1>

<div id="networkdeviceaddeditformoptions">
    <form method="post" action="" enctype="multipart/form-data">
    &nbspSelect NetworkDevice: {{form.SelectNetworkDevice}} <br>
    <table>
    <tr><td>Network Device ID:</td><td>{{form.NetworkDeviceid}}</td></tr>
    </table>
</div>


<div id="networkdeviceaddeditformleftcolumn">
    <table>
    <tr><td>Name</td><td>{{form.Name}}</td></tr>
    <tr><td>Description</td><td>{{form.Description}}</td></tr>
    <tr><td>IP Address</td><td>{{form.IPAddress}}</td></tr>
    <tr><td>MACAddress</td><td>{{form.MACAddress}}</td></tr>
    <tr><td>DeviceModel</td><td>{{form.DeviceModel}}</td></tr>
    <tr><td>AMRSubstationName</td><td>{{form.AMRSubstationName}}</td></tr>
    <tr><td>ServiceTag</td><td>{{form.ServiceTag}}</td></tr>
    <tr><td>ServerIndicator</td><td>{{form.ServerIndicator}}</td></tr>
    </table>
</div>

<div id="networkdeviceaddeditformsubmit">
    New: {{form.NewIndicator}} Update: {{form.UpdateIndicator}} <input value="Submit" type="submit">
</div>
<br><br>
<div>
{{Repeating Block}}
</div>
</form>

{% endif %}


</body></html>
"""




NetworkDeviceAddEditFormRepeatingBlock="""
<li>New{{form.NewPortIndicator{{repeatnumber}}}}&nbspUpdate{{form.UpdatePortIndicator{{repeatnumber}}}}&nbspDelete{{form.DeletePortIndicator{{repeatnumber}}}}</li>
<li>Port ID{{form.Port_id{{repeatnumber}}}}</li>
<li>Port Name{{form.PortName{{repeatnumber}}}}</li>
<li>Description{{form.PortDescription{{repeatnumber}}}}</li>
<li>MAC Address{{form.PortMACAddress{{repeatnumber}}}}</li>
<li>IP Address{{form.PortIPAddress{{repeatnumber}}}}</li><br>
"""

def UpdateNetworkDeviceAddEditTemplate(NetworkDevicePorts, Username=''):
    FileName='/opt/coopip/djangoproject/templates/dynamic_networkdeviceaddedit' + Username + '.html'
    Total=0
    ReplacementBlockList=[]
    for i in range(0, len(NetworkDevicePorts) + 1):
        ReplacementBlockList.append(NetworkDeviceAddEditFormRepeatingBlock.replace('{{repeatnumber}}', str(Total)))
        Total=Total+1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=NetworkDeviceAddEditFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()



def UpdateOutdoorLightingBillingPhaseTableTemplate(Username, Conditions):
    FileName='/opt/coopip/djangoproject/templates/dynamic_outdoorlightingbillingphasetable_' + Username + '.html'
    Total = 0
    ReplacementBlockList=[]

    for i in range(0, len(Conditions)):
        NoteList=GIS.Coopgisconditionmemberdescriptionhistory.objects.filter(condition__id=Conditions[i].gisid).order_by('-id')
        NoteListStringList=[]
        #NoteListStringList.append('<table>')
        NoteListStringList.append('<tr><td>User/Date </td><td>Description</td></tr>')

        for note in NoteList:
            if(note.createusername):
                notename=str(note.createusername)
            else:
                notename=''
            if(note.createdatetime):
                notecreatedatetime=str(note.createdatetime)[:10]
            else:
                notecreatedatetime=''

            NoteListStringList.append('<tr><td>' + notename + ':  ' + notecreatedatetime + '</td><td>{% autoescape on %}' + str(note.description) + '{% endautoescape %}</td></tr>')
        #NoteListStringList.append('</table>')
        
        ReplacementBlockList.append('<table border="1"><tr><th>Step 1 LocationFM</th><th>Step 2 MemberSep</th><th>Step 3 Outdoor Light</th></tr>' + 
                                     '<tr><td valign="top">' +  #Step 1 Column
                                        '<table>' + 
                                        '<tr><td>Update</td><td>{{form.UpdateIndicator' + str(i) + '}}</td></tr>' +
                                        '<tr><td>Complete CIS Location Setup</td><td>{{form.CISLocationSetupCompleteIndicator' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Member Owns Pole</td><td>{{form.gisoutdoorlightcustomerownspoleindicator' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Member Owns Light</td><td>{{form.gisoutdoorlightcustomerownslightindicator' + str(i) + '}}</td></tr>' +   
                                        '<tr><td>Retire</td><td>{{form.gisneedsretirementindicator' + str(i) + '}}</td></tr>' +
                                        '<tr><td>Light Map Number</td><td>{{form.gisoutdoorlightmapnumber' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Service Address</td><td>{{form.gistagnumber' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>District</td><td> {{form.cismeterdistrict' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Tax</td><td>{{form.cismetertaxdistrict' + str(i) + '}}</td></tr>' +
                                        '<tr><td>County</td><td>{{form.cismetercountycode' + str(i) + '}}</td></tr>' +
                                        '<tr><td>Cycle</td><td>{{form.cismetercycle' + str(i) + '}}</td></tr>' +  
                                        '<tr><td>Transfer Station</td><td>{{form.giscircuitnumbers' + str(i) + '}}</td></tr>' +
                                        '<tr><td>Read Sequence</td><td>1</td></tr>' +  
                                        '<tr><td>MeterGuide</td><td>{{form.gisoutdoorlightmemberdescription' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Light</td><td>Utility</td></tr>' + 
                                        '<tr><td>Contract</td><td>Not Needed</td></tr>' + 
                                        '<tr><td>Pole Purpose</td><td>Outdoor Light</td></tr>' + 
                                        '<tr><td>Pole</td><td>{{form.gispolecompatibleunitname' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>Eng Substation</td><td>{{form.gissubstation' + str(i) + '}}</td></tr>' + 

                                        '<tr><td>id</td><td>{{form.id' + str(i) + '}}</td></tr>' + 
                                        '<tr><td>gisid</td><td>{{form.gisid' + str(i) + '}}</td></tr>' +
                                        '<tr><td>Station</td><td>{{form.gisstationidentifier' + str(i) + '}}</td></tr>' +  
                                        '</table>' + 
                                     '</td><td valign="top">' + #Step 2 Column
                                         '<table>' + 
                                         '<tr><td>Lights in CIS Start</td><td>{{form.LightsOriginallyInCIS' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Lights in CIS End</td><td>{{form.LightsFinallyInCIS' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Complete Membersep Changes</td><td>{{form.CISMemberSeparatorSetupCompleteIndicator' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Meter Number</td><td>{{form.gisoutdoorlightmeternumber' + str(i) + '}}</td></tr>' + 
                                    
                                         '<tr><td>Member Seperator</td><td>{{form.cismemberseperator' + str(i) + '}}</td></tr>' + 
                                         '<tr><td><a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q={{Coordinates.Longitude' + str(i) + '}}W+{{Coordinates.Latitude' + str(i) + 
                                                   '}}N&sll={{Coordinates.Longitude' + str(i) + '}},{{Coordinates.Latitude' + str(i) + '}}" target="_blank">Road</a></td>' + 
                                                   '<td><a href="http://' + djangoproject.settings.COOPGISServerIPAddress + '/coopgis/viewer/{{Coordinates.Station' + str(i) + '}}/" target="_blank">GIS</a></td></tr>' + 
                                         '<tr><td>Lights Owned by Member</td><td>{{form.gisoutdoorlightconsumerownedlightcount' + str(i) + '}}</td></tr>' + 
                                         '</table>' +
                                     '</td><td valign="top">' + #Step 3 Column
                                         '<table>' + 
                                         '<tr><td>CIS Billing Setup Complete</td><td>{{form.BillingSetupCompleteIndicator' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Conversion Notes</td><td>{{form.Coopgisconditionmemberdescriptionhistory' + str(i) + '}}</td></tr>' +
                                         '<tr><td>Retire Light to GIS</td><td>{{form.SendRetirementToGISIndicator' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>CISLocation</td><td>{{form.cislocation' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Additional Billing Poles</td><td>{{form.gisoutdoorlightadditionalbillingpolecount' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Outdoor Light ID</td><td>{{form.gisoutdoorlightratename' + str(i) + '}}</tr></tr>' + 
                                         '<tr><td>Outdoor Light Number</td><td>0</tr></tr>' + 
 
                                         '<tr><td>Meter Map number</td><td>{{form.gisoutdoorlightmetermapnumber' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Idle</td><td>{{form.gisoutdoorlightidleindicator' + str(i) + '}}</td></tr>' +   
                                         '<tr><td>Field Date</td><td>{{form.giscreatedatetime' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Field User</td><td>{{form.giscreateusername' + str(i) + '}}</td></tr>' + 
                                         

                                         '<tr><td>Billing Setup Complete Date</td><td>{{form.BillingSetupCompleteDateTime' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>Billing Setup Username</td><td>{{form.BillingSetupCompleteUsername' + str(i) + '}}</td></tr>' +
                                         '<tr><td>Send Back to GIS</td><td>{{form.SendToGISIndicator' + str(i) + '}}</td></tr>' + 
                                         '<tr><td>' + ''.join(NoteListStringList) + '</td></tr>' +  
                                         '<tr><td>&nbsp</td><td>&nbsp</td></tr>' + 
                                         '<tr><td>Delete {{form.DeleteIndicator' + str(i) + '}}</td><td>&nbsp </td></tr>' + 
                                         '</table>\n' + 
                                     '</tr></table>\n')




    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=DynamicFormTemplateLicenseBlock + OutdoorLightingBillingPhaseTableFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()

DynamicFormTemplateLicenseBlock="""
<!--
#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

"""


OutdoorLightingBillingPhaseTableFormTemplate="""
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>COOPIP Outdoor Lighting Billing Phase Form</title>
  </head>
  <body>
	<b>COOPIP Outdoor Lighting Billing Phase Table Form </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
 <table>
<tr><td>&nbsp</td><td><input value="Submit" type="submit"></td></tr>


{{Repeating Block}}

</table>
</form>
  </body>
</html>
"""





def UpdateAlarmTemplate(Username,Alarms):
    FileName='/opt/coopip/djangoproject/templates/dynamic_alarmtable_' + Username + '.html'
    Total = 0
    ReplacementBlockList=[]
    for i in range(0, len(Alarms)):
        RecentStatus=Alarms[i].GetRecentStatus()
        AlarmEventOpenIndicator=Alarms[i].GetAlarmEventOpenIndicator()
        if(AlarmEventOpenIndicator):
            alarmEventHistory=AlarmEventHistory.objects.filter(NetworkDevice=Alarms[i]).order_by('-StartDateTime')[0]
            EventTableData = ('<td>{{form.AlarmAcknowledgeIndicator' + str(i) + '}} ' + '</td>' +
                              '<td>{{form.AlarmCloseIndicator' + str(i) + '}} ' + '</td>'+
                              '<td>{{form.AlarmEventDescription' + str(i) + '}}<br>' + "Start Time: " + str(alarmEventHistory.StartDateTime) +
                                                                                     "<br>Acknowledge Time:  " + str(alarmEventHistory.AcknowledgeDateTime) + 
                                                                                     "<br>Disarm Time:  " + str(alarmEventHistory.DisarmDateTime) +  '</td>')
        else:
            EventTableData = """<td>&nbsp</td>
                                <td>&nbsp</td>
                                <td>&nbsp<br>No Current Events</td>"""
        
        ReplacementBlockList.append('<tr><td>{{form.UpdateIndicator' + str(i) + '}}</td>' +
                                    '<td>{{form.Alarmid' + str(i) + '}}</td>' +
                                    '<td>' + Alarms[i].AMRSubstationName + '</td>' +
                                    '<td>' + RecentStatus[0] + '<br>' + RecentStatus[1] + '</td>' +
                                    '<td>{{form.AlarmArmIndicator' + str(i) + '}}</td>' +
                                    '<td>{{form.AlarmDisarmIndicator' + str(i) + '}}</td>' +
                                    EventTableData)
    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=AlarmFormTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()






AlarmFormTemplate="""
<!--
#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>COOPIP Alarm Table Form</title>
  </head>
  <body>
	<b>COOPIP Alarm Table Form </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
 <table>
<tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td><input value="Submit" type="submit"></td></tr>

<tr><th>Update</th><th>Alarm ID</th><th>Substation</th><th>Status</th><th>Arm</th><th>Disarm</th><th>Acknowledge Event</th><th>Close Event</th><th>Event Notes</th></tr>

{{Repeating Block}}

</table>

</form>

  </body>
</html>
"""

def UpdateAlarmContactTemplate(Username,Groups):
    FileName='/opt/coopip/djangoproject/templates/dynamic_alarmcontact_' + Username + '.html'
    Total = 0
    ReplacementBlockList=[]
    for i in range(0, len(Groups)):
        ReplacementBlockList.append('<tr><td>{{form.UpdateIndicator' + str(i) + '}}</td>' +
                                    '<td>{{form.Groupid' + str(i) + '}}</td>' +
                                    '<td>{{form.PriorityLevel' + str(i) + '}}</td>' +
                                    '<td>{{form.Recipients' + str(i) + '}}</td>' +
                                    '<td>{{form.EscalationIntervalSeconds' + str(i) + '}}</td></tr>')
    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=AlarmContactTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()


AlarmContactTemplate="""
<!--
#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>COOPIP Alarm Contact Group Form</title>
</head>
<body>
    <b>COOPIP Alarm Contact Group Form </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
<table>
    <tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td><input value="Submit" type="submit"></td></tr>
    <tr><th>Update</th><th>Group ID</th><th>Priority</th><th>Recipients</th><th>Interval</th></tr>
    {{Repeating Block}}
</table>
</form>
</body>
</html>
"""

def UpdateVehicleTemplate(Username,Vehicles):
    FileName='/opt/coopip/djangoproject/templates/dynamic_dispatcheditvehicles_' + Username + '.html'
    Total = 0
    ReplacementBlockList=[]
    for i in range(0, len(Vehicles)):
        ReplacementBlockList.append('<tr><td>{{form.UpdateIndicator' + str(i) + '}}</td>' +
                                    '<td>{{form.Vehicleid' + str(i) + '}}</td>' +
                                    '<td>{{form.Name' + str(i) + '}}</td>' +
                                    '<td>{{form.Number' + str(i) + '}}</td>' +
                                    '<td>{{form.LatestLogDateTime' + str(i) + '}}</td>' +
                                    '<td>{{form.Status' + str(i) + '}}</td>' + 
                                    '<td>{{form.NearestRoadName' + str(i) + '}}</td></tr>')
    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=VehicleTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()

VehicleTemplate="""
<!--
#    Copyright 2013 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>COOPIP View/Edit Vehicle Form</title>
</head>
<body>
    <b>COOPIP View/Edit Vehicle Form </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
Nearest Road is still <b>Experimental</b>.  Do not rely on for accurate location names.
<table>
    <tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td><input value="Submit" type="submit"></td></tr>
    <tr><th>Update</th><th>Vehicle ID</th><th>Name</th><th>Number</th><th>Latest Log</th><th>Status</th><th>Nearest Road</th></tr>
    {{Repeating Block}}
</table>
</form>
</body>
</html>
"""

def UpdateOutageAssignmentTemplate(Username,Logs):
    FileName='/opt/coopip/djangoproject/templates/dynamic_dispatcheditoutageassignment_' + Username + '.html'
    Total = 0
    ReplacementBlockList=[]
    for i in range(0, len(Logs)):
        ReplacementBlockList.append('<tr><td>{{form.UpdateIndicator' + str(i) + '}}</td>' +
                                    '<td>{{form.AssignedTo' + str(i) + '}}</td>' +
                                    '<td>{{form.AssignedDateTime' + str(i) + '}}</td>' +
                                    '<td>{{form.Incidentid' + str(i) + '}}</td>' +
                                    '<td>{{form.MapNumber' + str(i) + '}}</td>' +
                                    '<td>{{form.MeterNumber' + str(i) + '}}</td>' + 
                                    '<td>{{form.Logid' + str(i) + '}}</td>' + 
                                    '<td>{{form.CreateDateTime' + str(i) + '}}</td></tr>')
    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=OutageAssignmentTemplate.replace('{{Repeating Block}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()

OutageAssignmentTemplate="""
<!--
#    Copyright 2013 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
THIS FILE WAS DYNAMICALLY GENERATED BY THE DYNAMIC TEMPLATE INCLUDE
MODIFICATIONS TO THIS FILE WILL BE PERIODICALLY OVERWRITTEN!!!!!
MODIFY THIS TEMPLATE IN THE COOPIP_DYNAMICTEMPLATE.PY FILE
**************************************************************************
-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>COOPIP View/Edit Outage Assignments</title>
</head>
<body>
    <b>COOPIP View/Edit Outage Assignments </b> &nbsp&nbsp&nbsp&nbsp <small><a href="/coopip/">Main Menu</a></small>
<form method="post" action="">
<table>
    <tr><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td>&nbsp</td><td><input value="Submit" type="submit"></td></tr>
    <tr><th>Update</th>
        <th>Assigned To</th>
        <th>Time</th>
        <th>Incident</th>
        <th>Map #</th>
        <th>Meter #</th>
        <th><ID></th>
        <th>Created</th></tr>
    {{Repeating Block}}
</table>
</form>
</body>
</html>
"""

def UpdateVehicleLogMapFile(Username,Vehicles):
    FileName='/opt/coopip/mapserver/dynamic_vehiclelog_' + Username + '.map'
    Total = 0
    ReplacementBlockList=[]
    for i in range(0, len(Vehicles)):
        if i <= len(VehicleLogMapFileColorList):
            Color = VehicleLogMapFileColorList[i]
        else:
            Color = VehicleLogMapFileColorList[len(VehicleLogMapFileColorList) - 1]
        
        ReplacementBlock = VehicleLogMapFileReplacementBlock.replace('{{Color}}', Color).replace('{{VehicleNumber}}', Vehicles[i])
        ReplacementBlockList.append(ReplacementBlock)
    Total = Total + 1
    ReplacementBlockString=''.join(ReplacementBlockList)
    FinalTemplate=VehicleLogMapFileMain.replace('{{RepeatingBlock}}', ReplacementBlockString)
    try:
        os.remove(FileName)
    except OSError:
        pass
    TemplateFile=open(FileName, 'w')
    TemplateFile.write(FinalTemplate)
    TemplateFile.close()
    return FileName

#red, blue, green, purple, orange, pink
VehicleLogMapFileColorList = ['235 83 85', '105 158 202',  '121 195 119', '178 122 186', '255 159 64', '249 160 207']

VehicleLogMapFileReplacementBlock="""
    CLASS
        EXPRESSION ('[symbologyvisible]' eq 't' AND '[vehiclenumber]' eq '{{VehicleNumber}}' AND '[speed]' == '0')
        STYLE
            SYMBOL 'SQUARE'
            SIZE 10
            OUTLINECOLOR 255 255 255
            COLOR {{Color}}
        END
    END #CLASS
    CLASS
        EXPRESSION ('[symbologyvisible]' eq 't' AND '[vehiclenumber]' eq '{{VehicleNumber}}' AND '[speed]' != '0')
        STYLE
            SYMBOL 'CIRCLE'
            SIZE 5
            COLOR {{Color}}
        END
    END #CLASS
    CLASS
        EXPRESSION ('[symbologyvisible]' eq 't' AND '[vehiclenumber]' eq '{{VehicleNumber}}' AND '[symbologystopstartstate]' eq 'stop')
        STYLE
            SYMBOL 'TRIANGLE'
            SIZE 15
            COLOR {{Color}}
        END
    END #CLASS
    CLASS
        EXPRESSION ('[symbologyvisible]' eq 't' AND '[vehiclenumber]' eq '{{VehicleNumber}}' AND '[symbologystopstartstate]' eq 'start')
        STYLE
            SYMBOL 'TRIANGLE'
            SIZE 15
            COLOR {{Color}}
            ANGLE 180
        END
    END #CLASS
"""


VehicleLogMapFileMain="""
#    Copyright 2013 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.
MAP
    NAME COOPMap
    SIZE 1024 1024   
    MAP
    CONFIG "PROJ_LIB" "/usr/share/proj/"
    NAME "COOPMap"
    FONTSET /opt/coopip/mapserver/fontset.txt
    SIZE 1024 1024
    # UNITS feet
    UNITS meters
    # EXTENT -82 33 -79 35
    EXTENT -9107000 3922000 -8865000 4126000

PROJECTION
  'proj=merc'
  'a=6378137'
  'b=6378137'
  'lat_ts=0.0'
  'lon_0=0.0'
  'x_0=0.0'
  'y_0=0'
  'units=m'
  'k=1.0'
  'nadgrids=@null'
  'no_defs'
END



#IMAGECOLOR 210 180 140  # Background color for the map canvas
IMAGEQUALITY 100
IMAGETYPE png
OUTPUTFORMAT
    NAME png
    DRIVER 'GD/PNG'
    MIMETYPE 'image/png'
    IMAGEMODE PC256
    EXTENSION 'png'
    FORMATOPTION 'INTERLACE=OFF'
    TRANSPARENT ON
END #OUTPUTFORMAT

FONTSET "/opt/coopip/mapserver/fontset.txt"
    LEGEND
    IMAGECOLOR 255 255 255
    STATUS ON
    KEYSIZE 18 12
    LABEL
        TYPE BITMAP
        SIZE MEDIUM
        COLOR 0 0 89
        MINDISTANCE 5
    END #LABEL
END #FONTSET

WEB
    IMAGEPATH '/var/www/tmp/'
    IMAGEURL '/tmp/'
    METADATA
        'wms_title'           'COOPMap'
        'wms_onlineresource'  'http://my.host.com/cgi-bin/mapserv?map=wms.map&'
        'wms_srs'             'EPSG:4326'
    END
END #WEB

LAYER
    NAME 'VehicleLog'
    TYPE POINT
    CONNECTIONTYPE postgis
    CONNECTION 'host=localhost user=coopipdbuser password=SLIPT2007 dbname=coopip'
    DATA 'the_geom FROM public.vehiclelog'
    METADATA
        'wms_title' 'VehicleLog'
    END
    STATUS DEFAULT
    TRANSPARENCY 70
    LABELMAXSCALE 60000
    PROJECTION
        'proj=lcc'
        'lat_1=34.83333333333334'
        'lat_2=32.5'
        'lat_0=31.83333333333333'
        'lon_0=-81'
        'x_0=609600'
        'y_0=0'
        'ellps=GRS80'
        'datum=NAD83'
        'to_meter=0.3048'
        'no_defs'
        ''
    END #PROJECTION
    {{RepeatingBlock}}
END #LAYER

#determine symbols and add here
SYMBOL
    NAME 'CIRCLE'
    TYPE ellipse
    FILLED true
    POINTS
        1 1
    END
END 

SYMBOL
    NAME "TRIANGLE"
    TYPE vector
    FILLED true
    POINTS
        0 0
        20 10
        20 -10
        0 0
        -99 -99
        -20 0
    END
END 

SYMBOL
    NAME 'SQUARE'
    TYPE VECTOR
    POINTS
        0 0
        0 1
        1 1
        1 0
        0 0
    END
    FILLED TRUE
END
END #MAP

"""


